#pragma once

#ifndef DISTANCE_MEASUREMENT_HANDLER_H_
#define DISTANCE_MEASUREMENT_HANDLER_H_

#include <osg/LineWidth>
#include <osg/Point>
#include <osg/ShapeDrawable>
#include <osg/BlendFunc>
#include <osgViewer/Viewer>
#include <osgGA/GUIEventHandler>
#include <osgUtil/Optimizer>
#include "DistanceDialog.h"
#include <osgFX/Scribe>

class DistanceMeasurementHandler :public osgGA::GUIEventHandler
{
public:
	DistanceMeasurementHandler();

	bool handle(const osgGA::GUIEventAdapter&ea, osgGA::GUIActionAdapter&aa);

	osg::Geode*GetPolyLineGeode();

	double distance;

	void Clear();

private:
	struct geometryUpdateCallback : public osg::Drawable::UpdateCallback
	{
		geometryUpdateCallback() { _numVertices = 0; _validity1 = _validity2 = false; }

		virtual void update(osg::NodeVisitor *nv, osg::Drawable *drawable);
		void SetValidity(bool val);


	private:
		bool         _validity1, _validity2;
		unsigned int _numVertices;
	};

	bool _getIntersectPoint(osgViewer::Viewer *viewer, const osgGA::GUIEventAdapter &ea, osg::Vec3d &intersectPoint, bool needCheck = false);


	osg::ref_ptr<osg::Geode>         _polygonGeode;
	osg::ref_ptr<osg::Geometry>      _geometry;
	osg::ref_ptr<osg::Vec3Array>     _vertexArray;
	osg::ref_ptr<osg::Vec4Array>     _colorArray;
	osg::ref_ptr<osg::StateSet>      _stateSet;
	osg::ref_ptr<osg::LineWidth>     _stateAttr_lineWidth;
	osg::ref_ptr<osg::Point>         _stateAttr_point;
	osg::ref_ptr<osg::DrawArrays>    _drawArrays_line;
	osg::ref_ptr<osg::DrawArrays>    _drawArrays_point;

	osg::ref_ptr<geometryUpdateCallback> _geomUpdateCallback;

	osg::Vec4 _color_normal, _color_end;

	float _x, _y;
	bool _isDrawing;
	bool _hasFinishedValidDrawing;

	double Distance(osg::Vec3Array *PolyLineVertex);
};
#endif